from fastapi import APIRouter, Request, HTTPException, Header

from backend.const import *
from backend.error import error_pydantic_msg
from backend.exception import DuplicateError
from backend.handler import (
    HandleTrainTaskInfo, 
    HandleTrainTaskQuery,
    HandleTrainTaskAdd, 
    HandleTrainTaskUpdate, 
    HandleTrainTaskStart, 
    HandleTrainTaskStatus,
)
from backend.model import *
from common.response import OkResponse, OkDuplicateAddResponse, BadRequestResponse, ServerErrorResponse


router = APIRouter()

'''
'任务状态：unstart未开始/training训练中/finished训练完成/error训练过程任意错误的情况',

调用：https://www.yuque.com/gaochao-5ifko/kb/ewdsgnnlr4cp8t53
1、task/launch  
2、task/status 前端的刷新逻辑，需要跟前端确定一下

'''


@router.get("/info")
def task_info(page_id: int = 1, page_size: int = 5, page_total: int = 0):
    # 校验参数是否正确 page_size不能为0，否则查询无意义
    if page_size <= 0:
        page_size = DEFAULT_PAGE_SIZE
    if page_id < 1:
        page_id = DEFAULT_PAGE_ID  # page_id默认页码号从1开始
    try:
        return OkResponse(data=HandleTrainTaskInfo(page_id=page_id, page_size=page_size, page_total=page_total))
    except ValidationError as e:
        import traceback
        traceback.print_exc()  # 联调用
        return ServerErrorResponse(data=error_pydantic_msg(e))
    except Exception as e:
        print(repr(e))
        return ServerErrorResponse(data=repr(e))


@router.get("/query")
def task_query(id: int):
    try:
        return OkResponse(data=HandleTrainTaskQuery(id))
    except ValidationError as e:
        import traceback
        traceback.print_exc()  # 联调用
        return ServerErrorResponse(data=error_pydantic_msg(e))
    except Exception as e:
        print(repr(e))
        return ServerErrorResponse(data=repr(e))


@router.post("/add")
def task_add(post_body: TrainTask):
    print(type(post_body), post_body)
    '''TODO post_body传参错误时，应返回参数错误，而不是直接进程挂掉导致报Internal Server Error
    添加middleware来处理
    '''
    try:
        return OkResponse(data=HandleTrainTaskAdd(post_body))
    except DuplicateError as e:
        return OkDuplicateAddResponse()
    except ValidationError as e:
        return ServerErrorResponse(data=error_pydantic_msg(e))
    except Exception as e:
        return ServerErrorResponse(data=repr(e))


@router.post("/update")
def task_update(post_body: TrainTask):
    print(type(post_body), post_body)
    '''TODO post_body传参错误时，应返回参数错误，而不是直接进程挂掉导致报Internal Server Error
    添加middleware来处理
    '''
    try:
        return OkResponse(data=HandleTrainTaskUpdate(post_body))
    except ValidationError as e:
        return ServerErrorResponse(data=error_pydantic_msg(e))
    except Exception as e:
        return ServerErrorResponse(data=repr(e))


@router.post("/start")
def task_start(data: dict):
    '''TODO post_body传参错误时，应返回参数错误，而不是直接进程挂掉导致报Internal Server Error
    添加middleware来处理
    '''
    print(data)
    try:
        return OkResponse(data=HandleTrainTaskStart(data['id']))
    except ValidationError as e:
        return ServerErrorResponse(data=error_pydantic_msg(e))
    except Exception as e:
        return ServerErrorResponse(data=repr(e))


@router.get("/status")
def task_status(id: int):
    print(id)
    '''TODO post_body传参错误时，应返回参数错误，而不是直接进程挂掉导致报Internal Server Error
    添加middleware来处理
    '''
    try:
        return OkResponse(data=HandleTrainTaskStatus(id=id))
    except ValidationError as e:
        import traceback
        traceback.print_exc()  # 联调用
        return ServerErrorResponse(data=error_pydantic_msg(e))
    except Exception as e:
        print(repr(e))
        return ServerErrorResponse(data=repr(e))


if __name__ == '__main__':
    print(','.join([1,2]))